import React, { Component } from 'react'
import { connect } from 'dva';
import { Card, Button, message, Table, Divider, Tooltip, Form, Input, DatePicker, Popconfirm, Modal } from 'antd'
import { CloseCircleOutlined, DownloadOutlined, ExclamationCircleOutlined, CopyOutlined } from '@ant-design/icons';
import moment from 'moment';
import { CopyToClipboard } from 'react-copy-to-clipboard';

import formatSeconds from '@/utils/formatSeconds'
import Player from './components/Player'

import styles from './index.less'
import { formatMessage } from 'umi-plugin-locale'


const { RangePicker } = DatePicker;

@connect(({ video, loading }) => ({
  video,
  loading: loading.effects['video/fetchVideoList']
}))
class Playback extends Component {

  columns = [
    
    {
      title: `${formatMessage({'id':'playback.table.police_name'})}`,
      dataIndex: 'plcName',
      key: 'plcName',
    },
    {
      title: `${formatMessage({'id':'playback.table.police_no'})}`,
      dataIndex: 'plcNo',
      key: 'plcNo',
    },
    {
      title: `${formatMessage({'id':'playback.table.device_sn'})}`,
      dataIndex: 'devSN',
      key: 'devSN',
    },
    {
      title: `${formatMessage({'id':'playback.table.filename'})}`,
      dataIndex: 'fileName',
      key: 'fileName',
      width: 280,
      render: (text, record) => {
        return (
          <div className='flex inline-item'>
            {record.fileName}
            <Tooltip title={formatMessage({'id':'playback.table.copy_address'})}>
              <CopyToClipboard text={record.fileUrl}
                onCopy={this.onCopy.bind(this)}>
                <Button type="link" size="sm" icon={<CopyOutlined />}></Button>
              </CopyToClipboard>
            </Tooltip>
          </div>
        )
      }
    },
    {
      title: `${formatMessage({'id':'playback.table.filesize'})}`,
      dataIndex: 'fsize',
      key: 'fsize',
      sorter: true,
      align: "right",
      render: val => <span>{val = (Math.max(val, 0) / 1024 / 1024).toFixed(2) + "MB"}</span>,
    },
    {
      title: `${formatMessage({'id':'playback.table.duration'})}`,
      dataIndex: 'duration',
      key: 'duration',
      align: 'right',
      render: (text, record) => {
        let { hour, minute, second } = formatSeconds(record.duration)
        return (
          <span>{hour > 0 && hour + '小时'}{minute}分{second}秒</span>
        )
      }
    },
    {
      title: `${formatMessage({'id':'playback.table.time'})}`,
      key: 'sDate',
      dataIndex: 'sDate',
      sorter: true,
      align: "center",
    },
    {
      title: `${formatMessage({'id':'playback.table.action'})}`,
      key: 'action',
      align: "center",
      width: 180,
      render: (text, record) => (
        <span>
          
          <a href="#play" disabled={record.enable === 0} onClick={() => { this.handlePlay(record) }}>播放</a>

          {/* 分割线 UI组件 */}
          <Divider type="vertical" />
          <a href="#download" disabled={record.enable === 0} onClick={() => { this.handleDownload(record) }}>下载</a>
          <Divider type="vertical" />
          <Popconfirm placement='left' onConfirm={() => this.delete(record)} title={formatMessage({'id':'playback.confirm_delete_file'})}>
            <a href="#delete" disabled={record.enable === 0}>{formatMessage({'id':'common.button.remove'})}</a>
          </Popconfirm>
        </span>
      )
    }
  ]

  state = {
    loading: false,
    selectedRowKeys: [],
    selectedRows: [],
    showPlayer: false,
    fileInfo: false,
  }

  formRef = React.createRef();

  componentDidMount() {
    this.querySearch()
  }


  onChangeDate(value, dateString) {
    // console.log('Selected Time: ', value);
    // console.log('Formatted Selected Time: ', dateString);
  };

  onCopy() {
    message.success('复制成功')
  }

  //查询参数
  query = {

  };

  setQuery = (query) => {
    this.query = query
  }


  //数据查询方法
  querySearch = () => {
    this.setState({ loading: true })
    this.props.dispatch({
      type: 'video/fetchVideoList',
      payload: this.query,
      callback: (res) => {
        this.setState({ loading: false })
      }
    })

  }

  onFinish = values => {
    let deviceSn = values.deviceSn,
      policeNo = values.policeNo,
      realname = values.policeName,
      startTime = values.rangeTime[0].format("YYYY-MM-DD HH:mm:ss"),
      endTime = values.rangeTime[1].format("YYYY-MM-DD HH:mm:ss")

    let query = {
      deviceSn, policeNo, realname, startTime, endTime
    };

    this.setQuery(query);
    this.querySearch();

  }

  onTableChange = (pagination, filter, sorter) => {
    this.setQuery({
      ...this.query,
      page: pagination.current,
      perPage: pagination.pageSize,
      sort: sorter.field ? sorter.field : undefined,
      order: sorter.order === 'descend' ? 'desc' : (sorter.order === 'ascend' ? 'asc' : undefined)
    })
    this.querySearch();
  }

  resetForm = () => {
    this.formRef.current.resetFields()
    this.setQuery({
      startTime: this.query.startTime,
      endTime: this.query.endTime
    });
    this.querySearch();
  }

  delete(record) {
    this.props.dispatch({
      type: 'video/delete',
      payload: {
        id: record.id,
      },
      callback: res => {
        message.success(`${formatMessage({'id':'playback.delete_success'})}`);
        this.querySearch();
      },
    });
  }

  bulkDelete = () => {
    let _this = this;
    Modal.confirm({
      title: `${formatMessage({'id':'playback.confirm_delete_all_file'})}`,
      icon: <ExclamationCircleOutlined />,
      content: `${formatMessage({'id':'playback.not_recovery'})}`,
      onOk() {
        let selectedRowKeys = _this.state.selectedRowKeys
        _this.props.dispatch({
          type: 'video/bulkDelete',
          payload: {
            'id[]': selectedRowKeys,
          },
          callback: res => {
            message.success(`${formatMessage({'id':'playback.delete_success'})}`);
            _this.querySearch();
          },
        });

      },
    });

  }

  handlePlay(record) {

    this.props.dispatch({
      type: 'video/fetchVideoInfo',
      payload: {
        id: record.id,
      },
      callback: res => {
        if(res.code == 0) {

          this.setState({
            showPlayer: true,
            fileInfo: res.data
          })
        } else {
          message.error(`${formatMessage({'id':'playback.get_fileinfo_fail'})}`);
        }
      },
    });

    
  }

  handleViewClose() {
    this.setState({
      showPlayer: false,
    })
  }

  handleDownload(record) {
    fetch(record.fileUrl)
      .then(res => res.blob())
      .then(blob => {
        const a = document.createElement('a');
        document.body.appendChild(a)
        a.style.display = 'none'
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = record.fileName;
        a.click();
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url);
      }).catch(function (error) {
        message.success(`${formatMessage({'id':'playback.download_fail'})}`);
      });
  }

  bulkDownload() {
    const selectRows = this.state.selectedRows;
    if (selectRows) {
      selectRows.forEach(item => {
        this.handleDownload(item)
      })
    }
  }


  // 结构视图
  render() {
    const { videoList } = this.props.video
    const { list, pagination } = videoList

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRowKeys,
          selectedRows
        })
      }
    };

    return (
      <div className='p16'>

        {/* 这是上面的搜索以及日期栏 */}
        <Card bordered={false} style={{ marginBottom: 16 }}>
          <Form
            ref={this.formRef}
            layout={'inline'}
            onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}
            initialValues={{ rangeTime: [moment().subtract(6, 'days'), moment()] }}
          >
            <Form.Item name="policeName" label={formatMessage({ id: 'common.policeName' })}>
              <Input />
            </Form.Item>
            <Form.Item name="policeNo" label={formatMessage({ id: 'common.policeNo' })}>
              <Input />
            </Form.Item>
            <Form.Item name="deviceSn" label={formatMessage({ id: 'common.deviceSn' })}>
              <Input />
            </Form.Item>
            <Form.Item name="rangeTime" label={formatMessage({ id: 'common.datetime' })}>
              <RangePicker
                showTime={{ format: 'HH:mm' }}
                format="YYYY-MM-DD HH:mm"
                placeholder={[formatMessage({ id: 'common.starttime' }), formatMessage({ id: 'common.endtime' })]}
                onChange={this.onChangeDate}
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">{formatMessage({ id: 'common.button.ok' })}</Button>
              <Button type="default" htmlType="button" onClick={this.resetForm.bind(this)} style={{ marginLeft: '8px' }}>{formatMessage({ id: 'common.button.reset' })}</Button>
            </Form.Item>
          </Form>
        </Card>

        {/* 这是下面的警员信息列表 */}
        <Card bordered={false}>
          <div className={styles.toolsBtn}>
            {/* 删除按钮 */}
            <Button type="primary" disabled={this.state.selectedRowKeys.length === 0} danger style={{ marginRight: 16 }} onClick={this.bulkDelete.bind(this)}>
              <CloseCircleOutlined /> {formatMessage({ id: 'common.button.remove' })}
            </Button>

            {/* 下载按钮 */}
            <Button type="primary" disabled={this.state.selectedRowKeys.length === 0} onClick={this.bulkDownload.bind(this)}>
              <DownloadOutlined /> {formatMessage({ id: 'common.button.download' })}
            </Button>
          </div>

          <Table
            size="small"
            loading={this.state.loading}
            rowKey={record => record.id}
            rowSelection={rowSelection}
            bordered columns={this.columns}
            dataSource={list}
            onChange={this.onTableChange.bind(this)}
            pagination={pagination}
          />
        </Card>

        {
          this.state.showPlayer &&
          <Player fileInfo={this.state.fileInfo} handleClose={this.handleViewClose.bind(this)} />
        }

      </div >
    )
  }
}
export default Playback